// pages/venue/map.js
const api = require('../../utils/api');

Page({
  data: {
    venueId: null,
    currentCity: '长沙',
    venueInfo: {},
    latitude: 28.228209,
    longitude: 112.938814,
    markers: [],
    loading: true
  },

  onLoad: function(options) {
    // 获取门店ID
    if (options.id) {
      this.setData({
        venueId: options.id
      });
      
      // 加载门店详情
      this.loadVenueDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }

    // 获取当前城市
    const app = getApp();
    if (app.globalData.currentCity) {
      this.setData({
        currentCity: app.globalData.currentCity
      });
    }
  },
  
  // 加载门店详情
  loadVenueDetail: function() {
    wx.showLoading({
      title: '加载中...',
    });
    
    api.venue.getVenueDetail(this.data.venueId)
      .then(res => {
        if (res && res.success && res.data) {
          const venueInfo = res.data;
          
          // 设置地图中心点和标记
          const markers = [{
            id: venueInfo.id,
            latitude: venueInfo.latitude,
            longitude: venueInfo.longitude,
            width: 30,
            height: 30,
            callout: {
              content: venueInfo.name,
              color: '#000000',
              fontSize: 14,
              borderRadius: 4,
              padding: 8,
              display: 'ALWAYS',
              textAlign: 'center'
            }
          }];
          
          this.setData({
            venueInfo: venueInfo,
            latitude: venueInfo.latitude,
            longitude: venueInfo.longitude,
            markers: markers,
            loading: false
          });
        } else {
          wx.showToast({
            title: '获取门店信息失败',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(err => {
        console.error('获取门店信息失败:', err);
        wx.showToast({
          title: '获取门店信息失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  // 返回上一页
  onTapBack: function() {
    wx.navigateBack();
  },
  
  // 导航到门店
  onTapNavigation: function() {
    wx.openLocation({
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      name: this.data.venueInfo.name,
      address: this.data.venueInfo.address,
      scale: 18
    });
  },
  
  // 拨打电话
  onTapCall: function() {
    wx.makePhoneCall({
      phoneNumber: this.data.venueInfo.phone || '400-123-4567'
    });
  },
  
  // 前往预定
  onTapBookNow: function(e) {
    const venueId = e.currentTarget.dataset.venueId;
    wx.reLaunch({
      url: '/pages/venue/room?venueId=' + venueId
    });
  }
})